<template>
  <div class="diagonsticView">
    <div class="header-view">
      <h3>{{ header }}</h3>
      <el-button
        :disabled="disabled"
        :type="d.loading ? 'danger' : 'primary'"
        size="default"
        @click="$emit('toDiagnostic')"
      >
        {{ diagnosticTips }}
      </el-button>
    </div>
    <div
      v-loading="d.loading"
      element-loading-text="病历选项有改动，请点击诊断按钮重新生成"
      element-loading-spinner="null"
    >
      <EMRCell
        v-for="(item, index) in data"
        :key="index"
        :data="item.data"
        :ref="setDiagnosticsRefs"
        :disabled="disabled"
        @clickEvent="emrCellClick"
      ></EMRCell>
    </div>
    <scrollDialog
      :title="dialogTitle"
      v-model:dialogVisible="dialogVisible"
      @clickSubmit="dialogSubmitClick"
    >
      <template #headerBtn>
        <el-button
          :type="dislogData ? 'primary' : ''"
          text
          @click="switchChange"
        >
          <svg-icon style="margin-left: 5px" icon-class="switchLoad"></svg-icon>
          {{ dislogData ? '同步最新评估表' : '同步当前病历选项' }}
          <!-- <el-icon class="el-icon--left"><Sort /></el-icon> -->
        </el-button>
      </template>
      <control-level-form
        ref="dialogFormRef"
        v-if="dialogType === 'control'"
        isDialog
        :showType="showType"
        :id="controlId"
        :pid="pid"
        :initData="dislogData"
        :emrId="emrId"
        :recordDate="recordDate"
        @success="controlSuccess"
        @scrollEvent="scrollEvent"
      ></control-level-form>
      <bronchial-asthma-form
        ref="dialogFormRef"
        v-if="dialogType === 'acute' && showType === 'lessThan'"
        isDialog
        :showType="showType"
        :id="acuteId"
        :pid="pid"
        :initData="dislogData"
        :recordDate="recordDate"
        :emrId="emrId"
        @success="acuteSuccess"
        @scrollEvent="scrollEvent"
      ></bronchial-asthma-form>
      <bronchialAsthmaFormSA
        ref="dialogFormRef"
        v-if="dialogType === 'acute' && showType === 'greaterEqual'"
        isDialog
        :showType="showType"
        :id="acuteId"
        :pid="pid"
        :initData="dislogData"
        :emrId="emrId"
        :recordDate="recordDate"
        @success="acuteSuccess"
        @scrollEvent="scrollEvent"
      ></bronchialAsthmaFormSA>
    </scrollDialog>
  </div>
</template>
<script>
  import { computed, reactive, watch, ref, nextTick, onMounted } from 'vue'
  import { useRouteAndRouter } from '@/hooks/core/useRouteAndRouter.js'
  import scrollDialog from '@/components/ScrollDialog'
  // eslint-disable-next-line max-len
  import controlLevelForm from '@/views/reception/components/form/controlLevelForm'
  // eslint-disable-next-line max-len
  import bronchialAsthmaForm from '@/views/reception/components/form/bronchialAsthmaForm'
  // eslint-disable-next-line max-len
  import bronchialAsthmaFormSA from '@/views/reception/components/form/bronchialAsthmaFormSA'
  import { useStore } from 'vuex'
  import { diffTimesToYear } from '@/utils/timeTools'
  import { scrollToClassName, emrScrollIndex } from '@/utils/domScroll'
  import {
    getLocalControLevel,
    acuteControlLevels,
  } from '@/utils/lib/EmrTextConvert/index'
  import common from '@/utils/common'
  export default {
    name: 'diagnosticView',
    props: {
      data: {
        type: Array,
        default() {
          return []
        },
      },
      title: {
        type: String,
        default() {
          return '诊断'
        },
      },
      disabled: Boolean,
      // 病历带过来 急性喘息发作id
      emrAcuteId: Number,
      // 病历带过来 控制水平id
      emrControlId: Number,
      // 患者id
      pid: Number,
      // 病历日期
      recordDate: String,
      attrs: Object,
      emrId: [String, Number],
    },
    components: {
      scrollDialog,
      controlLevelForm,
      bronchialAsthmaForm,
      bronchialAsthmaFormSA,
    },
    emits: ['toDiagnostic', 'updateAssessment'],
    setup(props, context) {
      const d = reactive({ loading: false, diagnosticsRefs: [] })
      const setDiagnosticsRefs = function (el) {
        if (el !== null && d.diagnosticsRefs.length < props.data.length)
          d.diagnosticsRefs.push(el)
      }
      const getData = function () {
        let newObj = {}
        d.diagnosticsRefs.forEach((ref) => {
          newObj = { ...newObj, ...ref.getData() }
        })
        return newObj
      }

      watch(
        () => props.data,
        (val, oldVal) => {
          if (oldVal && oldVal.length === 0) return
          d.loading = false
        },
        { deep: true }
      )

      // 风险筛查
      const { isRisk } = useRouteAndRouter()
      const risk = isRisk()
      const header = computed(() => {
        if (risk) {
          return '哮喘风险筛查'
        }
        return props.title
      })

      const diagnosticTips = computed(() => {
        if (risk) {
          return '生成哮喘风险筛查'
        }
        return '生成诊断报告'
      })
      const hidden = function () {
        d.loading = false
      }
      const reset = function () {
        d.loading = true
      }

      const dialogVisible = ref(null)
      const dialogType = ref(null)
      const dialogTitle = ref(null)
      // 界面显示的数据转换之后
      const dislogData = ref(null)
      const emrCellClick = async function (item) {
        const { name } = item
        const years = checkEmrYears(props.recordDate)

        if (name === 'clickControl') {
          dialogType.value = 'control'
          dialogTitle.value = '控制水平评估表'
          if (store.getters.controlDialogStatus) {
            dislogData.value = getLocalControLevel(props.attrs, years)
          } else {
            dislogData.value = null
          }
        } else if (name === 'clickacute') {
          dialogType.value = 'acute'
          dialogTitle.value =
            years >= 6
              ? '支气管哮喘急性发作严重度评估表'
              : '哮喘急性发作严重度评估表'

          if (store.getters.acuteDialogStatus) {
            dislogData.value = acuteControlLevels(props.attrs, years)
          } else {
            dislogData.value = null
          }
        }
        dialogVisible.value = true
      }

      const store = useStore()
      const switchChange = function () {
        const years = checkEmrYears(props.recordDate)
        if (dialogType.value === 'control') {
          if (dislogData.value) {
            dislogData.value = null
            store.dispatch('emr/setControlDialogStatus', false)
          } else {
            dislogData.value = getLocalControLevel(props.attrs, years)
            store.dispatch('emr/setControlDialogStatus', true)
          }
        } else if (dialogType.value === 'acute') {
          if (dislogData.value) {
            dislogData.value = null
            store.dispatch('emr/setAcuteDialogStatus', false)
          } else {
            dislogData.value = acuteControlLevels(props.attrs, years)
            store.dispatch('emr/setAcuteDialogStatus', true)
          }
        }
      }

      const showType = computed(() => {
        const years = checkEmrYears(props.recordDate)
        if (years < 6) {
          return 'lessThan'
        } else {
          return 'greaterEqual'
        }
      })

      function checkEmrYears(recordDate) {
        const birthday = store.getters.patientInfo.birthday
        const recordBirthday = store.getters.emrRecordBirthday
        // 时间以备份的时间为准
        const years = diffTimesToYear(recordDate, recordBirthday || birthday)
        return years
      }
      const acuteId = computed(() => {
        // 优先级最高是上一次本地暂存的数据，次一级是诊断的，最后都没有拿诊断的
        return store.getters.emrAcuteId
      })
      const controlId = computed(() => {
        return store.getters.emrControlId
      })

      const dialogFormRef = ref(null)
      const dialogSubmitClick = function () {
        console.log('点击了确定')
        dialogFormRef.value.onSubmit()
      }

      const controlSuccess = function (id) {
        // newControlId.value = id
        if (id) store.dispatch('emr/setControlId', { enumType: 1, id })
        dialogVisible.value = false
        dislogData.value = null
        context.emit('updateAssessment')
      }
      const acuteSuccess = function (id) {
        // newAcuteId.value = id
        // 急性喘息发作id
        if (id) store.dispatch('emr/setEmrAcuteId', { enumType: 1, id })
        dialogVisible.value = false
        dislogData.value = null
        context.emit('updateAssessment')
      }
      async function scrollEvent(name) {
        console.log('scrollEvent name =' + name)
        const tmp = {
          control1: '2',
          control2: '4',
          control3: '2',
          control4: '3',
        }
        common.XmAlert('选项与病历内容不符，是否前往调整病历', () => {
          dialogVisible.value = false
          // eslint-disable-next-line max-len
          const domClassName = `.content-wrapper:nth-child(${emrScrollIndex[name]})`
          scrollToClassName(domClassName, name)
        })
      }
      return {
        d,
        setDiagnosticsRefs,
        getData,
        reset,
        hidden,
        header,
        diagnosticTips,
        emrCellClick,
        dialogVisible,
        showType,
        acuteId,
        controlId,
        dialogType,
        dialogSubmitClick,
        dialogFormRef,
        controlSuccess,
        acuteSuccess,
        dialogTitle,
        dislogData,
        switchChange,
        scrollEvent,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .diagonsticView {
    font-size: 18px !important;
    line-height: 18px;
    padding: 12px;
    margin: 0 0 12px 0;

    .header-view {
      display: flex;
      justify-content: start;
      align-items: center;

      h3 {
        margin: 0;
        line-height: 2;
        margin-right: 12px;
      }
    }

    :deep(.el-checkbox-group) {
      margin-bottom: 15px;
    }

    :deep(.el-loading-mask) {
      background-color: rgba(255, 255, 255, 0.9) !important;
      transition: opacity var(--el-transition-duration);
    }
  }
</style>
